<template>
  <div class="search">
    <!-- 搜索组件一级路由   $router.back()返回上一个页面-->
    <van-nav-bar
      left-arrow
      title="搜索中心"
      @click-left="$router.back()">
    </van-nav-bar>

    <!-- https://youzan.github.io/vant/#/zh-CN/search -->
    <van-search
      v-model.trim="keyword"
      show-action
      action-text="搜索"
      placeholder="请输入搜索关键词"
      shape="round"
      @input="inputFn"
      @search="search(keyword)"
    >
      <template #action>
        <div @click="search(keyword)">搜索</div>
      </template>
    </van-search>

    <!-- 联想建议 -->
    <van-cell-group v-if="keyword">
      <van-cell
        icon="search"
        v-for="(item, index) in sugList"
        :key="index"
        @click="search(item)"
        >
        <template #title>
          <div v-html="highLight(item)"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录">
      </van-cell>
      <van-cell :title="item" v-for="item in searchList" :key="item" @click="clickFn(item)">
        <van-icon name="close" @click.stop="del(item)" />
      </van-cell>
    </van-cell-group>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import { setHistory, getHistory } from '@/utils/storage'
import { getSuggestion } from '@/api/search'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '', // 搜索关键字
      sugList: [], // 推荐列表
      // 搜索关键字的数组
      searchList: getHistory()
    }
  },
  methods: {
    // 防抖节流优化input事件
    async inputFn() {
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (!this.keyword) {
          this.sugList = []
          return
        }
        const res = await getSuggestion(this.keyword)
        this.sugList = res.data.options
      }, 500)
    },
    // 高亮搜索的关键字
    highLight (str) {
      const reg = new RegExp(this.keyword, 'gi')
      return str.replace(reg, match => {
        return `<span style="color: red;">${match}</span>`
      })
    },
    search (keyword) {
      if (!keyword) return this.$toast('请输入关键字')
      // 添加历史记录
      this.searchList = this.searchList.filter(item => item !== keyword)
      this.searchList.unshift(keyword)
      // 存本地
      setHistory(this.searchList)
      // 最后需要跳转到搜索结果页面
      this.$router.push({
        path: '/search/result',
        query: {
          keyword
        }
      })
    },
    del (keyword) {
      this.searchList = this.searchList.filter(item => item !== keyword)
      setHistory(this.searchList)
    },
    clickFn (item) {
      console.log('下标', item)
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: item
        }
      })
    }
  }
}
</script>

<style lang="" scoped>

</style>
